package com.czk.gulimall.ware.listener;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.czk.common.to.mq.OrderTo;
import com.czk.common.to.mq.StockDetailTo;
import com.czk.common.to.mq.StockLockTo;
import com.czk.common.utils.R;
import com.czk.gulimall.ware.dao.WareSkuDao;
import com.czk.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.czk.gulimall.ware.entity.WareOrderTaskEntity;
import com.czk.gulimall.ware.feign.OrderFeignService;
import com.czk.gulimall.ware.feign.ProductFeignService;
import com.czk.gulimall.ware.service.WareOrderTaskDetailService;
import com.czk.gulimall.ware.service.WareOrderTaskService;
import com.czk.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/5/24 21:08
 */
@Slf4j
@Component
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private WareSkuDao wareSkuDao;
    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderFeignService orderFeignService;
    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 1 库存自动解锁
     * 下订单成功，库存解锁成功，接下来业务调用失败导致订单回滚，之前锁定的库存自动解锁
     * 2 订单失败
     * 单个，库存锁定失败，
     * 只要解锁库存消息失败，告诉消息队列不要删除
     * @param stockLockTo
     * @param message
     */
    @RabbitHandler
    public void handleStockLockRelease(StockLockTo stockLockTo, Message message, Channel channel) throws IOException {
        log.info("收到解锁库存消息");
        StockDetailTo detail = stockLockTo.getDetail();
        // 先查库
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detail.getId());
        /**
         * 1 订单情况
         *    没有这个订单，必须解锁
         *    有这个订单，查看订单状态：
         *      取消：解锁库存
         *      没取消：不能解锁库存
         */
        if (!Objects.nonNull(byId)) {
            // 解锁
            // 查看订单情况
            Long id = stockLockTo.getId();
            WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getById(id);
            String orderSn = wareOrderTaskEntity.getOrderSn();
            // 拿到订单信息
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                // 成功
                JSONObject jsonObject = (JSONObject) r.getData(new TypeReference<JSONObject>() {

                });
                if (jsonObject==null){
                    //
                    log.info("订单不存在");
                    // 订单取消，解锁库存
                    unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detail.getTaskId());
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                }else {
                    Integer status = jsonObject.getInteger("status");
                    if (status == 4) {
                        // 订单取消
                        if (byId.getLockStatus()!=null&&byId.getLockStatus()==1){
                            // 订单取消，解锁库存
                            unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detail.getTaskId());
                            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                        }

                    }
                }
            }
        } else {
            // 无需解锁
            log.info("库存锁定不存在，不用解锁");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }
    @RabbitHandler
    public void handlerOrderCloseRelease(OrderTo orderTo,Message message,Channel channel) throws IOException {
        log.info("收到订单关闭，准备解锁库存");
        try {
            wareSkuService.unlockStock(orderTo);
        }catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
    /**
     * 解锁库存
     *
     * @param skuId
     * @param wareId
     * @param num
     * @param taskDetailId
     */
    public void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        // 解锁
        wareSkuDao.unLockStock(skuId,wareId,num);
        // 更新库存工作单状态
        WareOrderTaskDetailEntity entity=new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        entity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(entity);
    }

}
